package com.xiaolin.oa.interceptor;

import com.xiaolin.oa.constants.AuthConstant;
import com.xiaolin.oa.utils.ContextUtil;
import com.xiaolin.oa.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaolin
 * @description 用户认证拦截器
 * @since 2024/7/29
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private ContextUtil contextUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(AuthConstant.TOKEN);
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        String userInfo = redisUtil.get(token);
        if (StringUtils.isBlank(userInfo)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        // 登录状态续期
        contextUtil.stayActive(30 * 60);
        return true;
    }
}
